 
#include "tcp.h"

static void init_tcp_node(db_ldata_pt pdata )
{
       if ((pdata->sock_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) 
    {
        printf("socker create error!\n");
        exit(0);
    }
    struct sockaddr_in servaddr;
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port   = htons(TCP_PORT);
    if (inet_pton(AF_INET, TCP_SERVER, &servaddr.sin_addr) <= 0 )
    {
        printf("net_pton error!\n");
        exit(0);
    }
    if (connect(pdata->sock_fd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
    {
        printf("connect error!\n");
        exit(0);
    }
} 

static int tcp_send(db_ldata_pt pdata,void* sendbuffer)
{
    int ret = write(pdata->sock_fd,sendbuffer,strlen(sendbuffer));
    if(ret<0)
    {
        printf("send error:%d result:%s'\n",errno, strerror(errno));
        exit(0);
    }
    else
    {
        printf("send success,send length :%d \n",ret);
    }
    return ret;
}

static db_ldata_t tcp_node= {
	.id		= RAW_TCP,
    .flag   = INUSE,
    .Init   = init_tcp_node,
    .SendFunction = tcp_send,
};
 
static void register_tcp_method( db_list_pt ptlist, void * pdata )
{
     if( ptlist==NULL)
    {
        errno = EINVAL;
        return ;
    }
    __db_list_insert_before(&ptlist,1,pdata);
}

 
void init_tcp(db_list_pt ptlist)
{
    register_tcp_method(ptlist,(void *)&tcp_node);
   // tcp_node.Init(&tcp_node);
}
